package com.surfilter.gsxt.crawler;

//import com.surfilter.funds.task.service.webcrawl.OprateException;
//import com.surfilter.funds.task.util.*;

import com.surfilter.gsxt.OprateException;
import com.surfilter.gsxt.util.ApplicationUtil;
import com.surfilter.gsxt.util.WebCrawlUtils;
import com.surfilter.pojo.GsxtObj;
import com.surfilter.pojo.GsxtTask;
import com.surfilter.service.TaskService;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.UUID;

public class RefereeGsxtCollectUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(RefereeGsxtCollectUtil.class);
	
	private WebCrawlUtils utils;

	private static ResourceBundle bundle = ResourceBundle.getBundle("collect-config");
	
	private static final String url = bundle.getString("url");

	private static final Integer retryNum = Integer.parseInt(bundle.getString("retry_num"));

	private static final Integer ajaxWait = Integer.parseInt(bundle.getString("ajax_wait"));

	private static final String inputSelector = bundle.getString("input_selector");

	private static final String companySelector = bundle.getString("company_selector");

	private static final String gsxtContentSelector = bundle.getString("gsxt_content_celector");

	private static final String searchButtonSelector = bundle.getString("search_button_selector");

	//#极验证码滑块选择器
	private static final String gee_code_slider_selector = bundle.getString("gee_code_slider_selector");

	//#极验证码fullbg选择器
	private static final String gee_code_fullbgslice_selector = bundle.getString("gee_code_fullbgslice_selector");

	//#极验证码bg选择器
	private static final String gee_code_bgslice_selector = bundle.getString("gee_code_bgslice_selector");

	private static final String gee_xpath = bundle.getString("gee_xpath");

	private static final String snapshotPath = bundle.getString("snapshot_path");

	private TaskService service = (TaskService) ApplicationUtil.getBean("taskService");

//	private static final Object lock = new Object();
	private static final String engineName = ResourceBundle.getBundle("system-config").getString("engine_name");



	public void openBrowser() throws OprateException, InterruptedException{
		utils = new WebCrawlUtils();
		utils.initDriverByPools();
	}

	public void closeBrowser(){
		utils.recoveryDriver();
	}

	public void ajaxWait(long time){
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}


	//openNewTab 输入点击的selector
	public void openNewTab(String clickSelector){
		try {
			Set<String> nowWindows = utils.getAllWindows();
			utils.findElementByCssSelector(clickSelector).click();
			Set<String> allWindows = utils.getAllWindows();
			allWindows.removeAll(nowWindows);
			String newWindow = (String) allWindows.toArray()[0];
			utils.switchToWindow(newWindow);
		}catch (Exception e){
			logger.error(e.getMessage());
		}
	}
	//信用网
	public String xywCrawler(GsxtTask task) throws InterruptedException, UnsupportedEncodingException {
		String companyName = task.getCompanyName();
		String emd5 = task.getEmd5();
		task.setEngineName(engineName);
		Document document = null;
		String innerHTML = null;
		try {
			logger.info("打开企业信用网首页");
			utils.openWebPage("http://www.bgcheck.cn/Index.html");
			Thread.sleep(5000);
			utils.inputStr(companyName,"#input_Search");
			//打开搜索列表页
			openNewTab("#buttonSearch");
			Thread.sleep(5000);
			String firstSelector = "#content1 > ul:nth-child(2) > li:nth-child(1) > a:nth-child(1)";
			if(utils.findElementByCssSelector(firstSelector) != null){
				openNewTab(firstSelector);
				Thread.sleep(5000);
//				utils.cutCurrentSitePicture("c:/","detail",".jpg");
				//获取详情页信息
				innerHTML = utils.getPageSource();
//				String listSelector = "#form1 > div:nth-child(3) > div > ul.bk > li:nth-child(2) > div:nth-child(2)";
//				String contentHtml = utils.findElementByCssSelector(listSelector).getAttribute("innerHTML");
				//转换成实体
//				document = Jsoup.parse(contentHtml);
				task.setGsxtStatus(2);
				task.setDoneTime(new Date());
				service.updateTaskStatus(task);
			}else{
				logger.info("没有查询到，该企业工商信息在企业信用网站上未知");
				task.setGsxtStatus(6);
				task.setDoneTime(new Date());
				service.updateTaskStatus(task);
			}
		}catch (Exception e){
			logger.info("采集失败 " + e.getMessage());
			task.setGsxtStatus(3);
			task.setDoneTime(new Date());
			service.updateTaskStatus(task);
			//截屏
			utils.cutCurrentSitePicture(snapshotPath, "ERROR-"+UUID.randomUUID().toString(),".jpg");
		}
		return innerHTML;
	}

	private GsxtObj xywToGsxtObj(Document document, String emd5) {
		GsxtObj result = new GsxtObj();
		if (null != document){
			Elements elements = document.select("#ul_Gs > li");
			result.setType("businessInfo");
			result.setEmd5(emd5);
			for(int i=0;i<elements.size();i++){
				String key = document.select(".manager-info > table > tbody > tr > th").get(i).text();
				String value = document.select(".manager-info > table > tbody > tr > td").get(i).text();
				if(key.contains("统一社会信用代码") || key.contains("企业信用代码")){
					result.setUscc(value);
				}else if(key.contains("注册号")){
					result.setRegNumber(value);
				}else if(key.contains("名称") || key.contains("企业名称")){
					result.setEname(value);
				}else if(key.contains("类型") || key.contains("企业类型")){
					result.setEtype(value);
				}else if(key.contains("法人代表") || key.contains("法定代表人") || key.contains("经营者") || key.contains("投资人") || key.contains("负责人") || key.contains("执行事务合伙人")){
					result.setLegalRep(value);
				}else if(key.contains("注册资本") || key.contains("成员出资总额")){
					result.setRegCaptial(value);
				}else if(key.contains("登记状态")){
					result.setBusinsessStatus(value);
				}else if(key.contains("成立日期") || key.contains("注册日期") || key.contains("成立时间")){
					result.setEstablishTime(value);
				}else if(key.contains("登记机关")){
					result.setRegAuthority(value);
				}else if(key.contains("营业期限自") || key.contains("合伙期限自") || key.contains("营业期限")){
					result.setIssueTime(value);
				}else if(key.contains("营业期限至") || key.contains("合伙期限至")){
					result.setBusinessTerm(value);
				}else if(key.contains("核准日期")){
					result.setApproveDate(value);
				}else if(key.contains("住所") || key.contains("经营场所") || key.contains("营业场所") || key.contains("主要经营场所") || key.contains("企业地址")){
					result.setAddress(value);
				}else if(key.contains("经营范围") || key.contains("业务范围")){
					result.setBusinessScope(value);
				}else if(key.contains("组成形式")){
					result.setConstitute(value);
				}
			}
			String ename = utils.findElementByCssSelector("body > div:nth-child(2) > div.detail-top-vip1.vip-normal > div > div.base-info.nobtns > h1").getText();
			result.setEname(ename);
			logger.info("获取到的公司名称为："+ename);
//			utils.cutCurrentSitePicture(snapshotPath, "详情页-"+UUID.randomUUID().toString(),".jpg");
			return result;
		}else{
			return null;
		}
	}
}
